<template>
  <div class="p-0 m-0">
    <n-form
      ref="formRef"
      :model="form"
      :rules="rules"
      label-placement="left"
      label-width="80"
      require-mark-placement="right-hanging"
    >
      <n-form-item label="登录ID" path="loginId">
        <n-input v-model:value="form.loginId" placeholder="请输入登录ID —— 卡密系统的账号ID" clearable size="medium" />
      </n-form-item>

      <n-form-item label="登录密钥" path="loginKey">
        <n-input
          v-model:value="form.loginKey"
          type="password"
          placeholder="请输入登录密钥 —— 卡密系统自行生成的密钥"
          show-password-on="click"
          clearable
          size="medium"
        />
      </n-form-item>

      <n-form-item :show-label="false">
        <div class="flex gap-4 w-full mt-2">
          <n-button v-if="rechargeUrl" type="error" class="flex-1" @click="openUrl(rechargeUrl)">
            充值续费
          </n-button>
          <n-button type="primary" :loading="loading" class="flex-1" @click="handleLogin">
            {{ loading ? '登录中...' : '登录' }}
          </n-button>
        </div>
      </n-form-item>
    </n-form>

    <n-alert v-if="error" :title="error" type="error" :closable="false" class="mt-4" />
    <n-alert
      v-if="successMsg"
      :title="successMsg"
      type="success"
      closable
      class="mt-4"
      @close="successMsg = ''"
    />
  </div>
</template>

<script setup lang="ts">
import { reactive, ref, onMounted } from 'vue'
import { NForm, NFormItem, NInput, NButton, NAlert, type FormInst, type FormRules } from 'naive-ui'
import { BrowserOpenURL } from '../../../wailsjs/runtime/runtime'
import { useAuth } from './useAuth'

interface Props {
  autoLogin?: boolean
  rechargeUrl?: string
}

const props = withDefaults(defineProps<Props>(), {
  autoLogin: true,
  rechargeUrl: 'https://env-00jxu65bfie3-static.normal.cloudstatic.cn/admin/index.html#/'
})

const emit = defineEmits<{
  'login-success': []
  'login-start': []
  'login-end': []
  'login-log': [log: { message: string; type: string }]
}>()

const formRef = ref<FormInst | null>(null)
const successMsg = ref('')

const form = reactive({
  loginId: '',
  loginKey: ''
})

const rules: FormRules = {
  loginId: [{ required: true, message: '请输入登录ID', trigger: 'blur' }],
  loginKey: [{ required: true, message: '请输入登录密钥', trigger: 'blur' }]
}

const { loading, error, login, saveCredentials, loadCredentials } = useAuth()

const sendLog = (message: string, type = 'info'): void => {
  emit('login-log', { message, type })
}

const handleLogin = async (): Promise<void> => {
  if (!formRef.value) return

  try {
    await formRef.value.validate()
  } catch {
    return
  }

  emit('login-start')
  sendLog('开始登录验证...', 'info')

  const result = await login(form)

  if (result.success) {
    sendLog('登录成功', 'success')
    await saveCredentials(form, true)
    sendLog('登录凭据已保存', 'success')
    successMsg.value = '登录成功！'
    setTimeout(() => emit('login-success'), 1000)
  } else {
    sendLog(`登录失败: ${result.message}`, 'error')
  }

  sendLog('登录验证完成', 'info')
  emit('login-end')
}

const openUrl = (url: string): void => {
  BrowserOpenURL(url)
}

onMounted(async () => {
  const credentials = await loadCredentials()
  if (credentials) {
    form.loginId = credentials.loginId
    form.loginKey = credentials.loginKey

    if (props.autoLogin && credentials.loginKey) {
      sendLog('检测到保存的登录凭据，开始自动登录...', 'info')
      setTimeout(() => handleLogin(), 500)
    }
  } else {
    sendLog('未找到保存的登录凭据,等待用户手动登录', 'info')
  }
})

// 重置表单
const resetForm = (): void => {
  form.loginId = ''
  form.loginKey = ''
  error.value = ''
  successMsg.value = ''
  if (formRef.value) {
    formRef.value.restoreValidation()
  }
}

defineExpose({
  clearSuccessMessage: () => {
    successMsg.value = ''
  },
  resetForm
})
</script>

